import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:hive/hive.dart';

class CollectionService {
  final Box<CollectionModel> _collectionBox = Hive.box<CollectionModel>(
    'collections',
  );
  final Box<VideoModel> _videoBox = Hive.box<VideoModel>('videos');
  final Box<TeamModel> _teamBox = Hive.box<TeamModel>('teams');
  final Box<SharePostModel> _shareBox = Hive.box<SharePostModel>('shares');
  final Box<ScanResultModel> _scanResultBox = Hive.box<ScanResultModel>(
    'scan_results',
  );

  // 获取或创建用户收藏
  Future<CollectionModel> getOrCreateUserCollection(String userId) async {
    try {
      return _collectionBox.values.firstWhere((c) => c.userId == userId);
    } catch (e) {
      // 用户没有收藏记录，创建新的
      final collection = CollectionModel(userId: userId);
      await _collectionBox.put(userId, collection);
      return collection;
    }
  }

  // 添加团队到收藏
  Future<void> addTeamToCollection(String userId, String teamId) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.addTeam(teamId);
    await _collectionBox.put(userId, collection);

    // 更新团队收藏状态
    final team = _teamBox.get(teamId);
    if (team != null && !team.isCollected) {
      team.isCollected = true;
      await _teamBox.put(teamId, team);
    }
  }

  // 添加分享到收藏
  Future<void> addShareToCollection(String userId, String shareId) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.addShare(shareId);
    await _collectionBox.put(userId, collection);

    // 更新分享收藏状态
    final share = _shareBox.get(shareId);
    if (share != null && !share.isCollected) {
      share.isCollected = true;
      await _shareBox.put(shareId, share);
    }
  }

  // 添加视频到收藏
  Future<void> addVideoToCollection(String userId, String videoId) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.addVideo(videoId);
    await _collectionBox.put(userId, collection);

    // 更新视频收藏状态
    final video = _videoBox.get(videoId);
    if (video != null && !video.isCollected) {
      video.isCollected = true;
      await _videoBox.put(videoId, video);
    }
  }

  // 添加扫描结果到收藏
  Future<void> addScanResultToCollection(
    String userId,
    String scanResultId,
  ) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.addScanResult(scanResultId);
    await _collectionBox.put(userId, collection);

    // 更新扫描结果收藏状态
    final scanResult = _scanResultBox.get(scanResultId);
    if (scanResult != null && !scanResult.isFavorite) {
      scanResult.isFavorite = true;
      await _scanResultBox.put(scanResultId, scanResult);
    }
  }

  // 从收藏中移除团队
  Future<void> removeTeamFromCollection(String userId, String teamId) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.removeTeam(teamId);
    await _collectionBox.put(userId, collection);

    // 更新团队收藏状态
    final team = _teamBox.get(teamId);
    if (team != null && team.isCollected) {
      team.isCollected = false;
      await _teamBox.put(teamId, team);
    }
  }

  // 从收藏中移除分享
  Future<void> removeShareFromCollection(String userId, String shareId) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.removeShare(shareId);
    await _collectionBox.put(userId, collection);

    // 更新分享收藏状态
    final share = _shareBox.get(shareId);
    if (share != null && share.isCollected) {
      share.isCollected = false;
      await _shareBox.put(shareId, share);
    }
  }

  // 从收藏中移除视频
  Future<void> removeVideoFromCollection(String userId, String videoId) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.removeVideo(videoId);
    await _collectionBox.put(userId, collection);

    // 更新视频收藏状态
    final video = _videoBox.get(videoId);
    if (video != null && video.isCollected) {
      video.isCollected = false;
      await _videoBox.put(videoId, video);
    }
  }

  // 从收藏中移除扫描结果
  Future<void> removeScanResultFromCollection(
    String userId,
    String scanResultId,
  ) async {
    final collection = await getOrCreateUserCollection(userId);
    collection.removeScanResult(scanResultId);
    await _collectionBox.put(userId, collection);

    // 更新扫描结果收藏状态
    final scanResult = _scanResultBox.get(scanResultId);
    if (scanResult != null && scanResult.isFavorite) {
      scanResult.isFavorite = false;
      await _scanResultBox.put(scanResultId, scanResult);
    }
  }

  // 获取用户收藏的团队
  List<TeamModel> getUserCollectedTeams(String userId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedTeamIds
          .map((id) => _teamBox.get(id))
          .where((team) => team != null)
          .cast<TeamModel>()
          .toList();
    } catch (e) {
      return [];
    }
  }

  // 获取用户收藏的分享
  List<SharePostModel> getUserCollectedShares(String userId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedShareIds
          .map((id) => _shareBox.get(id))
          .where((share) => share != null)
          .cast<SharePostModel>()
          .toList();
    } catch (e) {
      return [];
    }
  }

  // 获取用户收藏的视频
  List<VideoModel> getUserCollectedVideos(String userId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedVideoIds
          .map((id) => _videoBox.get(id))
          .where((video) => video != null)
          .cast<VideoModel>()
          .toList();
    } catch (e) {
      return [];
    }
  }

  // 获取用户收藏的扫描结果
  List<ScanResultModel> getUserCollectedScanResults(String userId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedScanResultIds
          .map((id) => _scanResultBox.get(id))
          .where((result) => result != null)
          .cast<ScanResultModel>()
          .toList();
    } catch (e) {
      return [];
    }
  }

  // 检查项目是否被收藏
  bool isTeamCollected(String userId, String teamId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedTeamIds.contains(teamId);
    } catch (e) {
      return false;
    }
  }

  bool isShareCollected(String userId, String shareId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedShareIds.contains(shareId);
    } catch (e) {
      return false;
    }
  }

  bool isVideoCollected(String userId, String videoId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedVideoIds.contains(videoId);
    } catch (e) {
      return false;
    }
  }

  bool isScanResultCollected(String userId, String scanResultId) {
    try {
      final collection = _collectionBox.values.firstWhere(
        (c) => c.userId == userId,
      );
      return collection.collectedScanResultIds.contains(scanResultId);
    } catch (e) {
      return false;
    }
  }

  // 创建示例收藏数据（开发测试用）
  Future<void> createSampleCollections() async {
    // 检查是否已存在收藏数据
    if (_collectionBox.isEmpty) {
      try {
        // 获取需要的服务
        final userService = UserService();
        final teamService = TeamService();
        final shareService = ShareService();
        final videoService = VideoService();
        final scanResultService = ScanResultService();

        // 查找Ezra用户
        final ezraUser = userService.getUserByUsername('lalala');
        if (ezraUser != null) {
          // 获取一些团队、分享和视频用于收藏
          final teams = teamService.getAllTeams();
          final shares = shareService.getAllShares();
          final videos = videoService.getAllVideos();

          // 收藏前两个团队
          if (teams.length >= 2) {
            await addTeamToCollection(ezraUser.id, teams[0].id);
            await addTeamToCollection(ezraUser.id, teams[1].id);
          }

          // 收藏前三个分享
          if (shares.length >= 3) {
            await addShareToCollection(ezraUser.id, shares[0].id);
            await addShareToCollection(ezraUser.id, shares[1].id);
            await addShareToCollection(ezraUser.id, shares[2].id);
          }

          // 收藏前两个视频
          if (videos.length >= 2) {
            await addVideoToCollection(ezraUser.id, videos[0].id);
            await addVideoToCollection(ezraUser.id, videos[1].id);
          }

          // 收藏一个扫描结果
          final scanResults = scanResultService.getAllScanResults();
          if (scanResults.isNotEmpty) {
            await addScanResultToCollection(ezraUser.id, scanResults[0].id);
          }
        }
      } catch (e) {
        print('创建示例收藏数据失败: $e');
      }
    }
  }
}
